import { load } from "cheerio";
import { Analyzer } from "./crawler";

interface Course {
  title: string;
  count: number;
}
interface CourseResult {
  time: number;
  data: Course[];
}
export default class WalkerAnalyzer implements Analyzer {
  private static instance: WalkerAnalyzer;
  public static getInstance() {
    if (!WalkerAnalyzer.instance) {
      WalkerAnalyzer.instance = new WalkerAnalyzer();
    }
    return WalkerAnalyzer.instance;
  }
  private constructor() {}
  private getCourseInfo(html: string) {
    const $ = load(html);
    const courseItems = $(".course-item");
    const courseInfos: Course[] = [];
    courseItems.map((index, element) => {
      const descs = $(element).find(".course-desc");
      const title = descs.eq(0).text();
      const count = parseInt(descs.eq(1).text().split("：")[1], 10);
      courseInfos.push({ title, count });
    });
    return {
      time: new Date().getTime(),
      data: courseInfos,
    };
  }

  public analyze(html: string) {
    const courseInfo = this.getCourseInfo(html);
    return JSON.stringify(courseInfo);
  }

  public merge(saved: string, justRetrived: string) {
    const fileContent = JSON.parse(saved);
    const courseInfo: CourseResult = JSON.parse(justRetrived);
    fileContent[courseInfo.time] = courseInfo.data;
    return JSON.stringify(fileContent);
  }
}
